package com.itheima.travel.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.travel.mapper.RouteMapper;
import com.itheima.travel.pojo.Route;
import com.itheima.travel.pojo.RouteExample;
import com.itheima.travel.req.RouteVo;
import com.itheima.travel.service.RouteService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *
 */
@Service
public class RouteServiceImpl implements RouteService {

    @Autowired
    private RouteMapper routeMapper;

    @Override
    public RouteVo findRouteById(RouteVo routeVo) {
        // 根据id查询线路信息
        Route route = routeMapper.selectByPrimaryKey(routeVo.getId());
        // 转换类型
        return BeanConv.toBean(route, RouteVo.class);
    }

    @Override
    public PageInfo<RouteVo> findRouteByPage(RouteVo routeVo, int pageNum, int pageSize) {

        // 分页查询，先将参数绑定到当前线程上
        PageHelper.startPage(pageNum,pageSize);
        // 拼接查询条件
        RouteExample routeExample = new RouteExample();
        RouteExample.Criteria criteria = routeExample.createCriteria();
        // 多条件查询，分页查询路线的时候是要分情况的
        // 如果不是空的就使用这个条件
        if (!EmptyUtil.isNullOrEmpty(routeVo.getCategoryId())){
            criteria.andCategoryIdEqualTo(routeVo.getCategoryId());
        }
        if(!EmptyUtil.isNullOrEmpty(routeVo.getRouteName())){
            criteria.andRouteNameLike("%"+routeVo.getRouteName()+"%");
        }
        if (!EmptyUtil.isNullOrEmpty(routeVo.getMinPrice())){
            criteria.andPriceGreaterThan(routeVo.getMinPrice());
        }
        if (!EmptyUtil.isNullOrEmpty(routeVo.getMaxPrice())){
            criteria.andPriceLessThan(routeVo.getMaxPrice());
        }

        // 条件查询
        List<Route> routeList = routeMapper.selectByExample(routeExample);
        PageInfo<Route> pageInfo = new PageInfo<>(routeList);
        // 创建返回结果对象
        PageInfo<RouteVo> resultPageInfo = new PageInfo<>();
        // 拷贝成员变量
        BeanConv.toBean(pageInfo,resultPageInfo);
        // 手动深度拷贝
        resultPageInfo.setList(BeanConv.toBeanList(pageInfo.getList(),RouteVo.class));
        return resultPageInfo;
    }
}
